package com.project.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.server.entity.ConsultationMessage;
import com.project.server.mapper.ConsultationMessageMapper;
import com.project.server.service.ConsultationMessageService;
import com.project.server.dto.MessageDTO;
import com.project.server.vo.ConsultationMessageVO;
//import com.project.server.util.TokenUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ConsultationMessageServiceImpl extends ServiceImpl<ConsultationMessageMapper,ConsultationMessage> implements ConsultationMessageService {
    private final ConsultationMessageMapper messageMapper;
//    private final TokenUtils tokenUtils;

    @Override
    public List<ConsultationMessageVO> getConsultationMessages(Long consultationId) {
        List<ConsultationMessage> messages = messageMapper.selectList(
            new LambdaQueryWrapper<ConsultationMessage>()
                .eq(ConsultationMessage::getConsultationId, consultationId)
                .orderByAsc(ConsultationMessage::getCreateTime)
        );

        return messages.stream().map(msg -> {
            ConsultationMessageVO vo = new ConsultationMessageVO();
            BeanUtils.copyProperties(msg, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Long sendMessage(Long consultationId, MessageDTO dto, Long userId) {

        ConsultationMessage message = new ConsultationMessage();
        message.setConsultationId(consultationId);
        message.setFromUserId(userId);
        message.setContent(dto.getContent());
        message.setType(dto.getType());
        message.setCreateTime(LocalDateTime.now());

        messageMapper.insert(message);
        return message.getId();
    }
}
